
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
# Copyright 2022 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import re
import jieba
import requests

def translate(chinese):
    # try:
    url = "https://fanyi.baidu.com/sug"

    data = {"kw": chinese.strip()}

    response = requests.post(url, data=data)

    json=response.json()
    # print(f'{chinese} => {json}')
    value=None
    if len(json['data'])>0:
        value = json['data'][0]['v'].split(";")[0]
    
        result = re.sub(r'[^a-zA-Z]*$', '', value)
        result = re.search(r'[a-zA-Z\s]*$', result)
        return result[0]
        
    if value:
        vs=value.strip().split(' ')
        return vs[len(vs)-1]
    else:
        first_half = chinese[:len(chinese)//2]
        second_half = chinese[len(first_half):]
        return translate(first_half)+' '+translate(second_half)

def parameterTranslate(s):
    # 使用中英文逗号分隔字符串s
    parts = re.split(r'[,，]', s)
    result = []
    for part in parts:
        # 如果字符串不是以“<”开头
        if '<' not in part and '>' not in part:
            
            # 判断里面有没有中文
            chinese = re.findall(r'[\u4e00-\u9fff]+', part)
            # print(f"{part}->{chinese}")
            if chinese:
                # 如果有责抽出中文
                for word in chinese:
                    seg = jieba.cut(word)
                    seg_list = list(seg)
                    cword=""
                    for seg in seg_list:
                        # print(seg)
                        cword+=" "+translate(seg)
                        # print(cword)
                    # 使用T()翻译后替换原来的中文
                    part = part.replace(word, cword)
        # 把处理后的字符串加入结果列表
        result.append(part)
    # 将字符串数组以英文逗号未分隔合并成一个字符串
    output = ','.join(result)
    return re.sub(' +', ' ', output).strip()